var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,
    $ = layui.jquery,
    laydate = layui.laydate,
    excel;
layui.use(["excel"], function () {
    excel = layui.excel;
})
lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});
function getAllJson(jsons) {
    let tmpitem = []
    for (let item of jsons) {
        let tmparr = {}
        tmparr["value"] = item["code"];
        tmparr["name"] = item["name"];
        if (item["users"]) {
            for (let it of item["users"]) {
                item["list"].push(it)
            }
        }
        if (item["list"] && item["list"].length) {
            tmparr["children"] = getAllJson(item["list"]);
            tmpitem.push(tmparr)
        } else {
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}

function getxmselect(el, name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        initValue:[user.code],
        tree: {
            show: true,
            showLine: true,
            showFolderIcon: true,
            indent: 20,
            expandedKeys: false
        },
        height: 'auto',
        data: data,
        on: function ({arr, change, isAdd}) {
            return this
        }
    })
}
function getxmselectCommon(el, name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon: true,
            indent: 20,
            expandedKeys: false
        },
        height: 'auto',
        data: data,
        on: function ({arr, change, isAdd}) {
            return this
        }
    })
}
let statusList_1=[];
let typeList_1=[];
let operationList_1=[];
let deptOperationList_1=[];

let warehouseList_2=[];

let operationList_3=[];
let deptOperationList_3=[];
let warehouseList_3=[];
let statusList_3=[];
let typeList_3=[];

layer.ready(function () {

    //单据类型
    let statusOptions = [
        {name: "草稿箱", value: "1"},
        {name: "待批箱", value: "2"},
        {name: "已批箱", value: "3"},
        {name: "完成箱", value: "4"},
        {name: "垃圾箱", value: "5"}
    ];
    statusList_1 = getxmselectCommon("#status_1", "status", statusOptions);
    statusList_3 = getxmselectCommon("#status_3", "status", statusOptions);
    //单据类型
    let typeOptions = [
        {name: "登记", value: "1"},
        {name: "领出", value: "2"},
    ];
    typeList_1 = getxmselectCommon("#type_1", "type", typeOptions);
    typeList_3 = getxmselectCommon("#type_3", "businessType", typeOptions);

    //获取资源仓库信息
    $.ajax({
        url:"resourceSamples/getResourceWarehouseInfo",
        success:function(data){
            if(data.status == 200){
                let warehouse = [];
                for(let i in data.data) {
                    let tmp = {
                        name: data.data[i].name,
                        value: data.data[i].code
                    }
                    warehouse.push(tmp);
                }

                warehouseList_2 = getxmselectCommon("#warehouseCode_2", "warehouseId", warehouse);
                warehouseList_3 = getxmselectCommon("#warehouseCode_3", "warehouseId", warehouse);
            }
        }
    });



    //获取当前用户的部门及人员结构树
    let treeList = getCurrentDepartmentUser();

    if (treeList && treeList.list) {
        let userTree = getAllJson(treeList.list);
        operationList_1=getxmselect("#operationCode_1", "operationCode", userTree);
        operationList_3=getxmselect("#operationCode_3", "operationCode", userTree);
    } else {
        operationList_1= getxmselect("#operationCode_1", "operationCode", [{name: user.name, value: user.code}])
        operationList_3= getxmselect("#operationCode_3", "operationCode", [{name: user.name, value: user.code}])
    }
    //获取当前用户所属部门树()
    let currentDeptTreeList = getAllUserDepartmentTree();
    if (currentDeptTreeList && currentDeptTreeList.list) {
        let deptTree = getAllJson(currentDeptTreeList.list);
        deptOperationList_1 = getxmselect("#deptOperationCode_1", "deptOperationCode", deptTree);
        deptOperationList_3 = getxmselect("#deptOperationCode_3", "deptOperationCode", deptTree);
    } else {
        deptOperationList_1 = getxmselect("#deptOperationCode_1", "deptOperationCode", [{name: user.name, value: user.code}]);
        deptOperationList_3 = getxmselect("#deptOperationCode_3", "deptOperationCode", [{name: user.name, value: user.code}]);
    }
    form.render('select');
});
form.render();//表单刷新
table.render({
    elem: '#samplemasterinformation'
    ,url: 'resourceSamples/getResourceSamplesListByPage'
    ,where:{operationCode : user.code}
    ,toolbar: '#samplemasterinformationtoolbar'
    ,cols: [[
        {checkbox: true, fixed: true}
        ,{field:'billNo', title:'单据编号',sort:true,event:'receiptnumber'}
        ,{field:'statusStr', title:'单据类型',sort:true}
        ,{field:'createDate', title:'创建时间'}
        ,{field:'operator', title:'操作员',sort:true}
        ,{field:'customerName', title:'客户名称',sort:true}
        ,{field:'typeStr', title:'业务类型',sort:true}
        ,{field:'memo', title:'备注',sort:true}
        ,{fixed: 'right', width:240, toolbar: '#samplemasterinformationeditor', title:'操作'}
    ]]
    ,id: 'samplemasterinformationtableid'
    ,height: $(document).height() - $('#samplemasterinformation').offset().top - 50
    ,page: true
    ,limit: 100
    ,limits: [100, 200, 300, 400, 500, 1000]
});
table.on('tool(samplemasterinformationtable)', function(obj){
    let data = obj.data;
    let id = data.id;
    let type = data.type;
    if(obj.event === 'update') {
        if(1 === type){
            //登记
            let count = getPlanCountByPurchaseNo(id);
            if (count) {
                layer.msg("已做领出，无法修改", {icon: 5});
            } else {
                parent.intab("views/jsp/WarehouseManagement/tpl/ResourceSamplesRegistrationUpdate.jsp?id=" + obj.data.id, "修改工厂仓库登记")
            }
        }else if(2 === type){
            //领出
            parent.intab("views/jsp/WarehouseManagement/tpl/ResourceSamplesTakeOutUpdate.jsp?id="+obj.data.id,"修改工厂仓库领出")
        }

    }else if(obj.event === 'delect'){
        layer.confirm("确认删除？",
            confirmInfo(3,6),
            function (index) {
                layer.close(index);
                let dataBases={
                    id:id,
                    status:data.status
                }
                $.ajax({
                    type:"POST",
                    dataType:"json",
                    contentType: 'application/json',
                    data:JSON.stringify(dataBases),
                    url:"resourceSamples/delete",
                    success:function(res){
                        if(res.status == 200){
                            layer.msg("删除成功", {icon: 6});
                            table.reload('samplemasterinformationtableid', {
                                page: {
                                    limit:10,
                                    curr: 1 //重新从第 1 页开始
                                }
                                ,where: data.field
                            }, 'data');
                            return false;
                        }else {
                            layer.msg(res.msg, {icon: 5});
                        }
                    }
                });
            });
    }else if(obj.event === 'submits'){
        layer.confirm('确定提交审批吗?', confirmInfo(3, 5), function (index) {
            operationData(id, type, 1, "提交审批");
        });
    }else if(obj.event === 'through'){
        layer.confirm('确定审批通过吗?', confirmInfo(3, 5), function (index) {
            operationData(id, type, 2, "审批通过");
        });
    }else if(obj.event === 'backtothe'){
        if (1 === type) {
            //登记
            let count = getPlanCountByPurchaseNo(id);
            if (count) {
                layer.msg("已做领出，无法退回", {icon: 5});
            } else {
                layer.confirm('确定审批退回吗?', confirmInfo(3, 5), function (index) {
                    operationData(id, type, 3, "审批退回");
                });
            }
        } else {
            //领出
            layer.confirm('确定审批退回吗?', confirmInfo(3, 5), function (index) {
                operationData(id, type, 3, "审批退回");
            });
        }
    }else if(obj.event === 'complete'){
        layer.confirm('确定完成吗?', confirmInfo(3, 5), function (index) {
            operationData(id, type, 4, "完成");
        });
    }else if(obj.event === 'reduction'){
        layer.confirm('确定还原吗?', confirmInfo(3, 5), function (index) {
            operationData(id, type, 5, "还原");
        });
    }else if(obj.event === 'receiptnumber'){
        parent.intab("views/jsp/WarehouseManagement/tpl/viewregistration.jsp?id="+obj.data.id,"工厂仓库明细")
    }
});

function operationData(id, type, operation, msg){
    let data = {
        id : id,
        type : type,
        operation: operation
    }
    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:JSON.stringify(data),
        url:"resourceSamples/operation",
        success:function(res){
            if(res.status == 200){
                layer.msg(msg, {icon: 6});
                table.reload('samplemasterinformationtableid', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where: data.field
                }, 'data');
                return false;
            }else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
}

//获取已做领出数量
function getPlanCountByPurchaseNo(id){
    let count = 0;
    $.ajax({
        url: "resourceSamples/getSampleTakeCountById?id=" + id,
        async: false,
        success: function (res) {
            if (res.status == 200) {
                count = res.data;
            } else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
    return count;
}

table.on('toolbar(samplemasterinformationtable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    var data = checkStatus.data;
    var id = "";
    if(data.length!=0){
        for(var i = 0;i<data.length;i++){
            if(i==data.length-1){
                id+=data[i].id;
            }else{
                id+=data[i].id+",";
            }
        }
    }
    switch(obj.event){
        case 'registration':
            parent.intab("views/jsp/WarehouseManagement/tpl/registration.jsp"+(id==''?'':'?id='+id),"新增工厂仓库登记")
            break;
        case 'bringforth':
            parent.intab("views/jsp/WarehouseManagement/tpl/bringforth.jsp"+(id==''?'':'?id='+id),"新增工厂仓库领出")
            break;
    };
});

form.on('submit(submit_form_1)', function(data){
    if(isEmpty(data.field.operationCode) && isEmpty(data.field.deptOperationCode) ){
        data.field.operationCode = user.code;
    }
    table.reload('samplemasterinformationtableid', {
        page: {
            curr: 1 //重新从第 1 页开始
        }
        ,where: data.field
    }, 'data');
    return false;
});

var cols = table.render({
    elem: '#sampleinventory',
    id: 'sampleinventorytableid',
    url: 'resourceSamples/getResourceSamplesStockListByPage',
    toolbar: '#sampleinventorytoolbar',
    cols: [[
        {field: 'img', title: '产品图片', align: 'center', templet: '#imgTpl'},
        {field: 'productCode', title: '产品编码'},
        {field: 'specificationCode', title: '规格编码'},
        {field: 'productCname', title: '中文名称'},
        {field: 'productEname', title: '英文名称'},
        {field: 'productCdesc', title: '中文描述'},
        {field: 'productEdesc', title: '英文描述'},
        {field: 'unitPrice', title: '单价'},
        {field: 'productNum', title: '数量'},
        {field: 'productUnit', title: '单位'},
        {field: 'articleNo', title: '货位'},
        {field: 'lotNo', title: '批次'},
        {field: 'warehouseName', title: '资源样品仓库'},
        {field: 'supplierName', title: '供应商'},
        {field: 'billNo', title: '单据编号'},
        {field: 'specificationExplanation', title: '备注'},
    ]],
    page: true,
    limit: 100,
    limits: [100, 200, 300, 400, 500, 1000],
    height: $(document).height() - 300
    , done: function (res, curr, count) {
        hoverOpenImg();//显示大图
    }
})

function hoverOpenImg() {
    var img_show = null; // tips提示
    $("body").delegate("td img", "mouseover", function () {
        var img = "<img class='img_msg' src='" + $(this).attr('src') + "' style='width:130px;' />";
        img_show = layer.tips(img, this, {
            tips: [2, 'rgba(41,41,41,.5)']
            , area: ['160px']
        });
    });
    $("body").delegate("td img", "mouseout", function () {
        layer.close(img_show);
    });
}


form.on('submit(submit_form_2)', function(data){
    table.reload('sampleinventorytableid', {
        page: {
            curr: 1 //重新从第 1 页开始
        }
        ,where: data.field
    }, 'data');
    return false;
});

//提示信息渲染
function confirmInfo(icon, anim) {
    let data = {
        icon: icon,
        title: "提示",
        offset: "auto",
        skin: 'layui-layer-molv',
        anim: anim
    }
    return data;
}


// 库存明细
table.render({
    elem: '#inventoryDetail',
    id: 'inventoryDetailId',
    url: 'resourceSamples/getInventoryDetailStatisticsReqListByPage',
    where:{operationCode : user.code},
    totalRow: true,
    cols: [[
        {field:'statusStr', title:'单据类型',sort:true,width: 110},
        {field:'billNo', title:'单据编号',sort:true,width: 150},
        {field:'typeStr', title:'业务类型',sort:true,width: 110},
        {field:'createDateStr', title:'创建日期',sort:true,width: 130},
        {field:'operationName', title:'操作员',sort:true,width: 120},
        {field: 'productCode', width: 120, title: '产品编码', sort: true},
        {field: 'detailWarehouseName', width: 160, title: '产品仓库', sort:true},
        {field: 'specificationCode', width: 180, title: '规格编码', sort: true},
        {field: 'productCname', width: 180, title: '中文名称', sort: true},
        {field: 'productEname', width: 180, title: '英文名称', sort: true},
        {field: 'productCdesc', width: 180, title: '中文描述', sort: true},
        {field: 'productEdesc', width: 180, title: '英文描述', sort: true},
        {field: 'unitPrice', width: 100, title: '单价', sort: true},
        {field: 'productNum', width: 100, title: '数量',sort: true,totalRow: true},
        {field: 'productUnit', width: 100, title: '单位', sort: true},
        {field: 'articleNo', width: 120, title: '货位', sort: true},
        {field: 'lotNo', width: 160, title: '批次', sort:true},
        {field: 'supplierName', width: 160, title: '供应商', sort:true},
        {field: 'specificationExplanation', width: 180, title: '备注', sort: true},
    ]],
    page: true,
    limit: 100,
    limits: [100, 200, 300, 400, 500, 1000],
    height: $(document).height() - 300
})
form.on('submit(submit_form_3)', function(data){
    if(isEmpty(data.field.operationCode) && isEmpty(data.field.deptOperationCode) ){
        data.field.operationCode = user.code;
    }
    table.reload('inventoryDetailId', {
        page: {
            curr: 1 //重新从第 1 页开始
        }
        ,where: data.field
    }, 'data');
    return false;
});
//产品导出excel
form.on('submit(exportData_3)', function (queryReq) {
    if(isEmpty(queryReq.field.operationCode) && isEmpty(queryReq.field.deptOperationCode) ){
        queryReq.field.operationCode = user.code;
    }

    let index = layer.load(2, {
        shade: [0.4, '#000'],
        content: '加载中...',
        success: function (layero) {
            layero.find('.layui-layer-content').css({
                'padding-top': '40px',
                'width': '200px'
            });
        }
    });
    $.ajax({
        data: queryReq.field,
        url: "resourceSamples/getInventoryDetailStatisticsReqListExport",
        success: function (res) {
            if (res.status == 200) {
                //配置列宽
                let colConf = excel.makeColConfig({
                    'A': 80,
                    'X': 80
                }, 80);
                excel.exportExcel({
                    sheet1: res.data.data
                }, '库存明细统计.xlsx', 'xlsx', {
                    extend: {
                        '!cols': colConf
                    }
                });
            } else {
                layer.msg(res.msg, {icon: 5});
            }
            layer.close(index);
            return false;
        }
    });
    return false;
});
//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}
document.getElementById('clear_1').onclick = function(){
    operationList_1.setValue([ ]);
    deptOperationList_1.setValue([ ]);
    statusList_1.setValue([ ]);
    typeList_1.setValue([ ]);
};
document.getElementById('clear_2').onclick = function(){
    warehouseList_2.setValue([ ]);
};

document.getElementById('clear_3').onclick = function(){
    operationList_3.setValue([ ]);
    deptOperationList_3.setValue([ ]);
    warehouseList_3.setValue([ ]);
    statusList_3.setValue([ ]);
    typeList_3.setValue([ ]);
};